<!--
 * 主页搜索栏
 * @Author: xurenda <xurenda@qq.com>
 * @HomePage: https://xurenda.top
 * @Github: https://github.com/xurenda
 * @Date: 2019-10-12 12:28:19
 * @LastEditTime: 2019-11-15 09:27:49
 * @FilePath: \elegant-surf\src\components\home\SearchBar.vue
 -->
<template>
<div id="search-bar" :style="style">
  <i class="iconfont icon-sousuo"></i>
  <input
    type="text"
    placeholder="键入空格以聚焦"
    ref="searchBar"
    v-model.lazy="query"
    @change="handleSearch"
  >
</div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'search-bar',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 搜索词
      query: this.value
    }
  },
  computed: {
    ...mapState({
      theme: state => state.appearanceSetting.theme, // 主题
      rounded: state => state.appearanceSetting.rounded // 圆角效果
    }),
    style() {
      let style = {}
      switch (this.theme) {
        case 'dark':
          style.backgroundColor = 'rgba(0, 0, 0, .5)'
          style.color = '#fff'
          break;
        case 'light':
          style.backgroundColor = 'rgba(255, 255, 255, .5)'
          break;
      }
      if (this.rounded) style.borderRadius = '100px'
      return style
    }
  },
  methods: {
    // 搜索栏提交触发事件
    handleSearch() {
      const keyword = this.query.trim()
      // this.$refs.searchBar.value = ''
      if (!keyword) return
      this.$router.push({
        path: '/search',
        query: { q: keyword }
      })
    },
    // keyup触发事件
    handleSearchKeyup(e) {
      if (e.keyCode !== 32) return
      this.$refs.searchBar.focus()
    }
  },
  mounted() {
    // 键入"空格"，搜索栏聚焦
    window.addEventListener('keyup', this.handleSearchKeyup)
  },
  beforeDestroy() {
    window.removeEventListener('keyup', this.handleSearchKeyup)
  }
}
</script>

<style lang="stylus">
#search-bar
  margin-top 100px
  margin-bottom 50px
  box-sizing border-box
  width 600px
  height 45px
  border-radius 6px
  padding 0 16px
  display flex
  align-items center
  i
    padding-right 10px
    font-weight 700
  input
    all unset
    flex 1
    height 45px
    line-height 45px
    font-size 14px
</style>